package com.touchportfolio.view
{
	import com.greensock.OverwriteManager;
	import com.greensock.TweenLite;
	import com.greensock.easing.*;
	import com.greensock.plugins.TintPlugin;
	import com.greensock.plugins.TweenPlugin;
	import com.touchportfolio.VO.NodeVO;
	import com.touchportfolio.events.PayloadEvent;
	import com.touchportfolio.loadQueue.LoadQueue;
	import com.touchportfolio.loadQueue.loaders.ImageLoader;
	import com.touchportfolio.model.ApplicationModel;
	import com.touchportfolio.model.SettingsModel;
	import com.touchportfolio.model.utils.EffectsUtilities;
	
	import flash.display.Bitmap;
	import flash.display.Sprite;
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.TimerEvent;
	import flash.geom.Point;
	import flash.utils.Timer;
	
	public class Row extends RowBasic
	{
		TweenPlugin.activate([TintPlugin]);
		OverwriteManager.init(OverwriteManager.NONE);
		
		public var _cImages:Sprite;
		
		private var _xOffset:Number = 0;
		private var _baseColor:Number;
		
		private var _isActive:Boolean;

		private var _c:Sprite = new Sprite();
		
		private var _slideshow:Sprite;
		private var _imageWrapper:Sprite;
		private var _cMask:Sprite;
		private var _cDummy:Sprite;
		private var _infoBalk:InfoBalk;
		private var _infoBarTimer:Timer;
		private var _imagesLoadedCounter:Number = 0;
		private var _imageXOffset:Number;
		private var _scale:Number;
		
		private var _thumbs:Array;
		private var _images:Array;
		private var _videos:Array;
		private var _media:Array;
		private var _activateScroll:Boolean;
		private var _bigImagesLoadedCount:uint;
		private var _slideshowWidth:Number = 0;
		private var _totalRealImages:Number = 0;
		private var _ticker:Timer;
		private var _startDragX:Number = 0;
		
		public function Row(node:NodeVO)
		{
			_node = node;
			
			_scale = nodeOpenImageHeight / nodeActiveHeight;
			
			drawRow();
			initSlideshowControls();
			
			_appModel = ApplicationModel.getInstance();
			_appModel.addEventListener(ApplicationModel.ACTIVE_ROW_CHANGE, onActiveRowChange);
			_appModel.addEventListener(ApplicationModel.ACTIVE_ROW_OPEN, onActiveRowOpen);
			_appModel.addEventListener(ApplicationModel.ACTIVE_ROW_CLOSE, onActiveRowClose);
			_appModel.addEventListener(ApplicationModel.NEXT_IMAGE, onNextImage);
			_appModel.addEventListener(ApplicationModel.PREVIOUS_IMAGE, onPreviousImage);
			_appModel.addEventListener(ApplicationModel.START_SLIDESHOW_DRAG, onStartSlideshowDrag);
			_appModel.addEventListener(ApplicationModel.STOP_SLIDESHOW_DRAG, onStopSlideshowDrag);
			_appModel.addEventListener(ApplicationModel.COLOR_CHANGE, colorChange);
			_appModel.stage.addEventListener(Event.RESIZE, onStageResize);
		}
		
		
		private function drawRow():void
		{
			_slideshow = new Sprite();
			addChild(_slideshow);
			
			_imageWrapper = new Sprite();
			_c = new Sprite();
			
			_cMask = new Sprite();
			_cMask.graphics.beginFill(0x00FF00);
			_cMask.graphics.drawRect(0, 0, 2000, nodeHeight);
			_cMask.graphics.endFill();
			
			var i:uint;
			_imageXOffset = 0;
			_imagesLoadedCounter = 0;
			_ticker = new Timer(25);
			_ticker.addEventListener(TimerEvent.TIMER, ticker);
			
			var imageLoaded:ImageLoader;
			_thumbs = [];
			var q:LoadQueue = LoadQueue.getInstance();
			
			
			for(i=0; i<node.media.length; i++)
			{					
				if(!node.media[i].video) imageLoaded = new ImageLoader(SettingsModel.getInstance().httpRoot + "thumbs/" + node.media[i].url);
				else
				{
					var videoNameArr:Array = node.media[i].url.split(".");
					imageLoaded = new ImageLoader(SettingsModel.getInstance().httpRoot + "thumbs/" + (node.media[i].url as String).substr(0, node.media[i].url.length-3) + "jpg");
				}
				
				imageLoaded.addEventListener(PayloadEvent.PAYLOAD, onImageLoaded);
				q.addTask(imageLoaded);
				imageLoaded.alpha = 0;
				_thumbs.push(imageLoaded);
				_c.addChild(imageLoaded);
				
				if(!node.media[i].video) _totalRealImages++;
			}
			
			
			// make dummy images
			_cDummy = new Sprite();
			_cDummy.alpha = 1;
			var dummy:DummyImage;
			for(i=0; i< 20; i++)
			{
				dummy = new DummyImage();
				dummy.x = i*dummy.width;
				dummy.y = -((dummy.height-nodeHeight)/2);
				_cDummy.addChild(dummy);
			}
			
			_c.addChild(_cDummy);
			
			EffectsUtilities.setSpriteToColor(_c, ApplicationModel.getInstance().color, 1);
			
			_c.mask = _cMask;
			_imageWrapper.addChild(_c);
			_imageWrapper.addChild(_cMask);
			_slideshow.addChild(_imageWrapper);
		}
		
		private function colorChange(e:Event):void{
			if(!_isActive){
				EffectsUtilities.setSpriteToColorTween(_c,ApplicationModel.getInstance().color,1,true,1);
				//EffectsUtilities.setSpriteToColor(_c, ApplicationModel.getInstance().color, 1);
			}
		}
		
		private function onImageLoaded(e:PayloadEvent):void
		{

			var bt:Bitmap = Bitmap(e.payload.content);
			bt.smoothing = true;
			bt.cacheAsBitmap = true;
			
			_thumbs[_imagesLoadedCounter].x = _imageXOffset;
			_thumbs[_imagesLoadedCounter].y = -((_thumbs[_imagesLoadedCounter].height-nodeHeight)/2);
			_imageXOffset += _thumbs[_imagesLoadedCounter].width;
			TweenLite.to(_thumbs[_imagesLoadedCounter], .2, {alpha:1});
			
			_slideshowWidth += _thumbs[_imagesLoadedCounter].width * _scale;
			_imagesLoadedCounter++;
			
			if(_imagesLoadedCounter >= _node.media.length)
			{
				_cDummy.x = _imageXOffset;
				TweenLite.to(_cDummy, .2, {alpha:1});
			}
		}
		
		private function initSlideshowControls():void
		{
			_infoBarTimer = new Timer(300, 1);
			_infoBarTimer.addEventListener(TimerEvent.TIMER_COMPLETE, showInfo);
			
			_infoBalk = new InfoBalk();
			if(_node.clientRow != true){
				_infoBalk.titelTxt.text = _node.title.toUpperCase();
				if(_node.title == "") _infoBalk.titelTxt.text = "NO TITLE"; 
				_infoBalk.clientTxt.text = _node.client.toUpperCase();
				if(_node.client == "") _infoBalk.clientTxt.text = "NO CLIENT";
			}
			
			
			_slideshowCloseBtn = new CloseButton();
			_slideshowCloseBtn.y = 25;
		}
		
		private function showInfo(e:TimerEvent = null):void
		{
			_infoBalk.y = nodeOpenImageHeight;
			_infoBalk.alpha = 0;
			TweenLite.to(_infoBalk, .15, {alpha:1});
			this.addChild(_infoBalk);
			
			_slideshowCloseBtn.x = _appModel.stage.stageWidth - _slideshowCloseBtn.width - 20;
			//this.addChild(_slideshowCloseBtn);
		}
		
		private function stopAllVideos():void
		{
			for(var i:uint=0; i<_videos.length; i++)
			{
				_videos[i].stopVideo(null);
				_videos[i].clearVideo();
			}
		}
		
		private function loadBigImages():void
		{
			_cImages = new Sprite();
			_images = [];
			_videos = [];
			_media = [];
			var bigImage:BigImage;
			var video:Video;
			_bigImagesLoadedCount = 0;
			
			for(var i:uint=0; i<_thumbs.length; i++)
			{
				if(!_node.media[i].video)
				{
					try {
					bigImage = new BigImage(SettingsModel.getInstance().httpRoot + node.media[i].url);
					bigImage.x = _thumbs[i].x*_scale;
					bigImage.addEventListener(BigImage.IMAGE_LOADED, onBigImageLoaded);
					_images.push(bigImage);
					_media.push(bigImage);
					_cImages.addChild(bigImage);}
					catch(e:TypeError){ trace("error loading image")}
				}
				else
				{
					try {
					video = new Video(SettingsModel.getInstance().httpRoot + node.media[i].url, _thumbs[i].width*_scale, _thumbs[i].height*_scale);
					video.x = _thumbs[i].x*_scale;
					_cImages.addChild(video);
					_videos.push(video);
					_media.push(video);}
					catch(e:TypeError){ trace("error loading video")}
				}
			}
			
			_appModel.slideshowReady = true;

			_slideshow.addChild(_cImages);
		}
		
		private function onBigImageLoaded(e:Event):void
		{
			_bigImagesLoadedCount++;
		}
		
		private function onNextImage(e:Event):void
		{
			if((_appModel.activeRow == _node.rowId && _appModel.slideshowReady) && (_thumbs.length) && (_slideshow.contains(_cImages)))
			{
				var nextX:Number = -_thumbs[_appModel.activeImage].x*_scale;
				if(nextX < -(_slideshowWidth - _appModel.stage.stageWidth)) {
					nextX = -(_slideshowWidth - _appModel.stage.stageWidth);
					//_appModel.activeImage--;
				}
				
				TweenLite.to(_slideshow, .5, {x:nextX, ease:Strong.easeOut});	
			}
		}
		
		private function onPreviousImage(e:Event):void
		{
			if((_appModel.activeRow == _node.rowId && _appModel.slideshowReady) && (_slideshow.contains(_cImages)))
				var prevX:Number = -_thumbs[_appModel.activeImage].x*_scale;
				TweenLite.to(_slideshow, .5, {x:prevX, ease:Strong.easeOut});
		}
		
		private function onActiveRowChange(e:Event):void
		{
			var i:uint = 0;
			
			if(_appModel.activeRow == _node.rowId)
			{
				TweenLite.to(_cMask,.6,{height:nodeActiveHeight, ease:Elastic.easeOut});
				for(i=0; i<_cDummy.numChildren; i++)
				{
					_cDummy.getChildAt(i).y = 0;
				}
				for(i=0; i<_thumbs.length; i ++)
				{
					_thumbs[i].y = 0;
				}
				
				EffectsUtilities.setSpriteToColorTween(_c,ApplicationModel.getInstance().color,0.2,false,1);
				
				_isActive = true;
			}
			else if(_isActive)
			{
				TweenLite.to(_cMask,1,{height:nodeHeight, ease:Elastic.easeOut, onComplete: function():void {
					// dirty hack
					TweenLite.to(_cMask, .3, {height:nodeActiveHeight, ease:Elastic.easeOut});
				}});
				
				for(i=0; i<_cDummy.numChildren; i++)
				{
					_cDummy.getChildAt(i).y = -((_cDummy.getChildAt(i).height-nodeHeight)/2);
				}
				for(i=0; i<_thumbs.length; i ++)
				{
					_thumbs[i].y = -((_thumbs[i].height-nodeHeight)/2);
				}
				
				EffectsUtilities.setSpriteToColor(_c, ApplicationModel.getInstance().color, 1);
				_isActive = false;
			}
		}
		
		private function onActiveRowOpen(e:Event):void
		{
			if((_appModel.activeRow == _node.rowId) && !_appModel.slideshowReady)
			{
				TweenLite.to(_imageWrapper,.5,{scaleY:_scale, scaleX:_scale, ease:Elastic.easeOut, onComplete:loadBigImages});
				_infoBarTimer.start();
				
				_appModel.activeImage = 0;
				_appModel.totalImages = _thumbs.length;
			}
		}
		
		private function onActiveRowClose(e:Event):void
		{
			if(_appModel.activeRow == _node.rowId)
			{
				if(this.contains(_infoBalk)) this.removeChild(_infoBalk);
				if(this.contains(_slideshowCloseBtn)) this.removeChild(_slideshowCloseBtn);
				if(this.contains(_slideshow) && (_slideshow.contains(_cImages))) _slideshow.removeChild(_cImages);
				
				_infoBarTimer.stop();
				stopAllVideos();
				_slideshow.x = 0;
				
				TweenLite.to(_imageWrapper,.6,{scaleY:1, scaleX:1, ease:Elastic.easeOut, onComplete:function():void{_slideshow.x = 0; _appModel.slideshowReady = false;}});
			}
		}
		
		private function onStartSlideshowDrag(e:Event):void
		{
			if((_appModel.activeRow == _node.rowId)  && _appModel.slideshowReady)
			{
				_startDragX = _appModel.stage.mouseX;
				_ticker.start();
			}
		}
		
		private function onStopSlideshowDrag(e:Event):void
		{
			if((_appModel.activeRow == _node.rowId) && _appModel.slideshowReady)
			{
				_ticker.stop();
				snap();
			}
		}
		
		private function ticker(e:TimerEvent):void
		{
			if((_appModel.activeRow == _node.rowId) && _appModel.slideshowReady)
			{
				var dif:Number = (_startDragX - _appModel.stage.mouseX); 
				TweenLite.to(_slideshow, .3, {x:_slideshow.x - dif*4});
				_startDragX -= dif;
			}
		}
		
		private function snap():void
		{
			var snapX:Number = 1000000000;
			var closestId:uint = 0;
			for(var i:uint=0; i<_media.length; i++)
			{
				var d:Number = Math.abs(_slideshow.x - (-_thumbs[i].x*_scale));
				if(d < snapX)
				{
					snapX = d;
					closestId = i;
				}
			}
			_appModel.activeImage = closestId;
		}
		
		private function onStageResize(e:Event):void
		{
			_slideshowCloseBtn.x = _appModel.stage.stageWidth - _slideshowCloseBtn.width - 20;
		}
	}
}